﻿using System;
using System.Data.Common;
using System.Reflection;

namespace UwaySoft.EsheetServer.DataLayer
{
    public class DataLayerHelper
    {
        private const string DataTypeIdentity = "DataLayer";
        private const string DataHelperFormat = "UwaySoft.EsheetServer.DataLayer.{0}.{0}Helper";

        public static ISqlHelper GetSqlHelper(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");

            var connectionStringBuilder = new DbConnectionStringBuilder {ConnectionString = connectionString};

            if(!connectionStringBuilder.ContainsKey(DataTypeIdentity))
                throw new ArgumentException("缺少数据库类型描述：DataLayer=?");

            var dbType = connectionStringBuilder[DataTypeIdentity].ToString();

            connectionStringBuilder.Remove(DataTypeIdentity);

            var helperTypeName = string.Format(DataHelperFormat, dbType);
            var assembly = Assembly.GetExecutingAssembly();
            var helperType = assembly.GetType(helperTypeName, true, true);
            var construct = helperType.GetConstructor(new[] {typeof (string)});

            if(construct == null)
                throw new Exception("construct");
            return (ISqlHelper)construct.Invoke(new object[] { connectionStringBuilder.ConnectionString });
        }
    }
}
